package vip.zhenzicheng.test.juc.lock.util;

import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 信号量,停车场模拟停车案例
 *
 * @author zhenzicheng
 * @date 2023-02-07 14:49
 */
public class SemaphoreCase {

  // 假设停车场最多能停放10台车
  private static final Semaphore semaphore = new Semaphore(10);

  public static void main(String[] args) {
    for (int i = 1; i <= 100; i++) {
      Thread thread = new Thread(() -> {
        System.out.println("====" + Thread.currentThread().getName() + "===");
        // 满了,没有车位
        if (semaphore.availablePermits() == 0) {
          System.out.println("车位不足，排队中");
        }
        try {
          // 尝试获取令牌
          semaphore.acquire();
          System.out.println(Thread.currentThread().getName() + "成功进入停车场");
          // 模拟停车时间
          Thread.sleep(ThreadLocalRandom.current().nextInt(3000));
          System.out.println(Thread.currentThread().getName() + "驶出停车场");
          // 释放令牌
          semaphore.release();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }, i + "号车");
      thread.start();
    }
  }
}
